package com.itheima.bos.service.system.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.system.MenuRepository;
import com.itheima.bos.dao.system.PermissionRepository;
import com.itheima.bos.dao.system.RoleRepository;
import com.itheima.bos.domain.system.Menu;
import com.itheima.bos.domain.system.Permission;
import com.itheima.bos.domain.system.Role;
import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleRepository roleRepository;
	
	@Autowired
	private PermissionRepository permissionRepository;

	@Autowired
	private MenuRepository menuRepository;
	
	@Override
	public List<Role> findByUser(User user) {
		
		if (user.getUsername().equals("admin")){
			return roleRepository.findAll();
		}
		return roleRepository.findByUser(user.getId());
	} 

	@Override
	public List<Role> findAll() {
		
		return roleRepository.findAll();
	}

	@Override
	public void save(Role model, String menuIds, String[] permissionIds) {
		
		//关联权限
		if (permissionIds != null){
			for (String permissionIdStr : permissionIds) {
				Integer permissionId = Integer.parseInt(permissionIdStr);
				Permission permission = permissionRepository.findOne(permissionId);
				model.getPermissions().add(permission);
			}
		}
		
		//关联菜单
		if (StringUtils.isNoneBlank(menuIds)){
			String[] split = menuIds.split(",");
			for (String menuIdStr : split) {
				Menu menu = menuRepository.findOne(Integer.parseInt(menuIdStr));
				model.getMenus().add(menu);
			}
		}
		
		//保存role
		roleRepository.save(model);
	}

}
